package cc.geguol.statement;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by 13687 on 2017/2/11.
 * 使用预编译 执行sql 语句
 */
public class PrepareStateDemo {
	private String uri="jdbc:mysql://localhost:3306/demo";
	private String user = "root";
	private String pwd = "root";
	private Connection conn;
	private PreparedStatement stmt;//连接

	/**
	 * @throws ClassNotFoundException
	 * dml
	 */
	@Test
	public void test2() throws ClassNotFoundException {
		//1.驱动注册程序
		Class.forName("com.mysql.jdbc.Driver");

		try{
			//2.获取连接对象
			conn = DriverManager.getConnection(uri, user, pwd);

			//3.预编译sql
			String sql="SELECT * FROM student where id=?";
			stmt = conn.prepareStatement(sql);

//			ResultSet resultSet = stmt.executeQuery(sql);
//			索引从1开始哦
			stmt.setString(1,"2");
//			执行sql
			ResultSet resultSet = stmt.executeQuery();
			if (resultSet.next())
			System.out.println("column2:"+resultSet.getString(2));


		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally {
			if (stmt!=null){
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}

			if (conn!=null){
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}



	}

}
